<template>
  <div class="order-management">
    <div class="header-actions">
      <h2>订单管理</h2>
    </div>

    <div class="search-bar">
      <input 
        type="text" 
        v-model="searchQuery" 
        placeholder="搜索订单号或用户名..."
        @input="handleSearch"
      >
      <select v-model="statusFilter" @change="handleSearch">
        <option value="">全部状态</option>
        <option value="pending">待处理</option>
        <option value="processing">处理中</option>
        <option value="completed">已完成</option>
        <option value="cancelled">已取消</option>
      </select>
    </div>

    <div class="orders-table">
      <table>
        <thead>
          <tr>
            <th>订单号</th>
            <th>用户</th>
            <th>商品</th>
            <th>总金额</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="order in filteredOrders" :key="order.id">
            <td>{{ order.id }}</td>
            <td>{{ order.username }}</td>
            <td>
              <div v-for="item in order.items" :key="item.id" class="order-item">
                {{ item.name }} x {{ item.quantity }}
              </div>
            </td>
            <td>¥{{ order.totalAmount }}</td>
            <td>
              <span :class="['status-badge', order.status]">
                {{ getStatusText(order.status) }}
              </span>
            </td>
            <td>{{ formatDate(order.createdAt) }}</td>
            <td>
              <button @click="viewOrderDetails(order)" class="view-btn">查看</button>
              <button 
                v-if="order.status === 'pending'"
                @click="updateOrderStatus(order.id, 'processing')" 
                class="process-btn"
              >
                处理
              </button>
              <button 
                v-if="order.status === 'processing'"
                @click="updateOrderStatus(order.id, 'completed')" 
                class="complete-btn"
              >
                完成
              </button>
              <button 
                v-if="['pending', 'processing'].includes(order.status)"
                @click="updateOrderStatus(order.id, 'cancelled')" 
                class="cancel-btn"
              >
                取消
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 订单详情对话框 -->
    <div v-if="showOrderDetails" class="dialog-overlay">
      <div class="dialog">
        <h3>订单详情</h3>
        <div v-if="selectedOrder" class="order-details">
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ selectedOrder.id }}</span>
          </div>
          <div class="detail-item">
            <span class="label">用户：</span>
            <span>{{ selectedOrder.username }}</span>
          </div>
          <div class="detail-item">
            <span class="label">创建时间：</span>
            <span>{{ formatDate(selectedOrder.createdAt) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">状态：</span>
            <span :class="['status-badge', selectedOrder.status]">
              {{ getStatusText(selectedOrder.status) }}
            </span>
          </div>
          <div class="detail-item">
            <span class="label">商品列表：</span>
            <div class="items-list">
              <div v-for="item in selectedOrder.items" :key="item.id" class="item">
                <img :src="item.image" :alt="item.name" class="item-image">
                <div class="item-info">
                  <div class="item-name">{{ item.name }}</div>
                  <div class="item-price">¥{{ item.price }} x {{ item.quantity }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="detail-item">
            <span class="label">总金额：</span>
            <span class="total-amount">¥{{ selectedOrder.totalAmount }}</span>
          </div>
        </div>
        <div class="dialog-actions">
          <button @click="showOrderDetails = false" class="close-btn">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { API_ENDPOINTS } from '../../api/config';
import axios from 'axios';

export default {
  name: 'OrderManagement',
  data() {
    return {
      orders: [],
      searchQuery: '',
      statusFilter: '',
      showOrderDetails: false,
      selectedOrder: null
    };
  },
  computed: {
    filteredOrders() {
      return this.orders.filter(order => {
        const matchesSearch = 
          order.id.toString().includes(this.searchQuery) ||
          order.username.toLowerCase().includes(this.searchQuery.toLowerCase());
        const matchesStatus = !this.statusFilter || order.status === this.statusFilter;
        return matchesSearch && matchesStatus;
      });
    }
  },
  methods: {
    async fetchOrders() {
      try {
        console.log('正在获取管理员订单列表...');
        const response = await axios.get(API_ENDPOINTS.ORDER.GET_ALL);
        console.log('管理员订单列表响应数据:', response.data);
        this.orders = response.data.map(order => ({
          ...order,
          totalAmount: parseFloat(order.totalAmount).toFixed(2),
          items: order.items ? order.items.map(item => ({
            ...item,
            image: item.image ? (item.image.startsWith('http') ? item.image : `http://localhost:3000${item.image}`) : null
          })) : []
        }));
      } catch (error) {
        console.error('获取订单列表失败:', error.response ? error.response.data : error.message);
        alert('获取订单列表失败');
      }
    },
    handleSearch() {
      // 搜索逻辑已通过计算属性实现
    },
    getStatusText(status) {
      const statusMap = {
        pending: '待处理',
        processing: '处理中',
        completed: '已完成',
        cancelled: '已取消'
      };
      return statusMap[status] || status;
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    viewOrderDetails(order) {
      this.selectedOrder = order;
      this.showOrderDetails = true;
    },
    async updateOrderStatus(orderId, newStatus) {
      try {
        console.log('正在更新订单状态:', { orderId, newStatus });
        const response = await axios.put(API_ENDPOINTS.ORDER.UPDATE_STATUS(orderId), {
          status: newStatus
        });
        
        console.log('更新订单状态响应:', response.data);
        
        if (response.data && response.data.message === '订单状态更新成功') {
          // 更新本地订单状态
          const order = this.orders.find(o => o.id === orderId);
          if (order) {
            order.status = newStatus;
          }
          alert('状态更新成功');
          // 刷新订单列表
          await this.fetchOrders();
        } else {
          throw new Error(response.data?.message || '更新状态失败');
        }
      } catch (error) {
        console.error('更新状态失败:', error);
        if (error.response?.data?.message) {
          alert(error.response.data.message);
        } else {
          alert('更新状态失败，请重试');
        }
      }
    }
  },
  created() {
    this.fetchOrders();
  }
};
</script>

<style scoped>
.order-management {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-actions {
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-bar input,
.search-bar select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-bar input {
  flex: 1;
}

.orders-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.order-item {
  margin-bottom: 4px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9em;
}

.status-badge.pending {
  background-color: #f1c40f;
  color: #fff;
}

.status-badge.processing {
  background-color: #3498db;
  color: #fff;
}

.status-badge.completed {
  background-color: #2ecc71;
  color: #fff;
}

.status-badge.cancelled {
  background-color: #e74c3c;
  color: #fff;
}

.view-btn,
.process-btn,
.complete-btn,
.cancel-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 8px;
}

.view-btn {
  background-color: #3498db;
  color: white;
}

.process-btn {
  background-color: #f1c40f;
  color: white;
}

.complete-btn {
  background-color: #2ecc71;
  color: white;
}

.cancel-btn {
  background-color: #e74c3c;
  color: white;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
}

.order-details {
  margin: 20px 0;
}

.detail-item {
  margin-bottom: 15px;
}

.label {
  font-weight: 500;
  margin-right: 10px;
}

.items-list {
  margin-top: 10px;
}

.item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
}

.item-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 500;
}

.item-price {
  color: #666;
  font-size: 0.9em;
}

.total-amount {
  color: #e74c3c;
  font-weight: bold;
  font-size: 1.2em;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.close-btn {
  padding: 8px 16px;
  background-color: #666;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style> 